package com.beyondsoft.common.core.sys.initialization;

import feign.Request;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

@Slf4j
@Configuration
public class FeignConfiguration implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames != null) {
            String thread = null;
            while (headerNames.hasMoreElements()) {
                String name = headerNames.nextElement();
                String values = request.getHeader(name);
                if (StringUtils.equals(name, "thread")) {
                    thread = values;
                } else {
                    requestTemplate.header(name, values);
                }
            }
            if (!StringUtils.equals(requestTemplate.method(), Request.HttpMethod.GET.name())) {
                //线程名
                if (thread != null) {
                    thread += ":" + Thread.currentThread().getId();
                } else {
                    thread = Thread.currentThread().getName();
                }
                requestTemplate.header("thread", thread);
            }
        }
        log.info("feign interceptor header:{}", requestTemplate);
    }

}
